function createCookie(name,value,days) {if (days) {var date = new Date();date.setTime(date.getTime()+(days*24*60*60*1000));var expires = "; expires="+date.toGMTString();}else var expires = "";document.cookie = name+"="+value+expires+"; path=/";}function readCookie(name) {var nameEQ = name + "=";var ca = document.cookie.split(';');for(var i=0;i < ca.length;i++) {var c = ca[i];while (c.charAt(0)==' ') c = c.substring(1,c.length);if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);}return null;}function eraseCookie(name) {createCookie(name,"",-1);}
/**
 * This jQuery plugin displays pagination links inside the selected elements.
 *
 * Modified by Carlo Tasca on 22-06-2009
 *
 * Modifications info:
 * ------------------------------
 * @author Gabriel Birke (birke *at* d-scribe *dot* de)
 * @version 1.2.1 (modified version of 1.2)
 * @param {int} maxentries Number of entries to paginate
 * @param {Object} opts Several options (see README for documentation)
 * @return {Object} jQuery Object
 */
jQuery.fn.pagination = function(maxentries, opts){
	opts = jQuery.extend({
		items_per_page:10,
		current_page:0,
		themeName:"white",
		callback:function(){return false;}
	},opts||{});
	
	return this.each(function() {
		/**
		 * Calculate the maximum number of pages
		 */
		function numPages() {
			return Math.ceil(maxentries/opts.items_per_page);
		}
		
		/**
		 * Calculate start and end point of pagination links depending on 
		 * current_page and num_display_entries.
		 * @return {Array}
		 */
		function getInterval()  {
			var ne_half = Math.ceil(opts.num_display_entries/2);
			var np = numPages();
			var upper_limit = np-opts.num_display_entries;
			var start = current_page>ne_half?Math.max(Math.min(current_page-ne_half, upper_limit), 0):0;
			var end = current_page>ne_half?Math.min(current_page+ne_half, np):Math.min(opts.num_display_entries, np);
			return [start,end];
		}
		
		/**
		 * This is the event handling function for the pagination links. 
		 * @param {int} page_id The new page number
		 */
		function pageSelected(page_id, evt){
			current_page = page_id;
			drawLinks();
			var continuePropagation = opts.callback(page_id, panel);
			return continuePropagation;
		}
		
	
		/**
		 * 刷新工具栏状态
		 */
		function refresh(){	

			if(current_page == 0 && current_page != numPages() -1){
				enabled();
				//btnGo.bind("mousedown",pressHandler);
				$(" ."+opts.themeName+"_pgPrev").addClass(opts.themeName+"_pgPrevDisabled");
				$(" ."+opts.themeName+"_pgFirst").addClass(opts.themeName+"_pgFirstDisabled");
			}else if(current_page != 0 && current_page == numPages() -1){
				enabled();
				//btnBack.bind("mousedown",pressHandler);
				$(" ."+opts.themeName+"_pgNext").addClass(opts.themeName+"_pgNextDisabled");
				$(" ."+opts.themeName+"_pgLast").addClass(opts.themeName+"_pgLastDisabled");
			}else if(current_page == 0 && current_page == numPages() -1){
				disabled();
			}else{
				enabled();
			}
		}
		
		/**
		   * 移除按钮disabled状态样式
		   */
		function enabled(){
				$(" ."+opts.themeName+"_pgNext").removeClass(opts.themeName+"_pgNextDisabled");
				$(" ."+opts.themeName+"_pgPrev").removeClass(opts.themeName+"_pgPrevDisabled");
				$(" ."+opts.themeName+"_pgFirst").removeClass(opts.themeName+"_pgFirstDisabled");
				$(" ."+opts.themeName+"_pgLast").removeClass(opts.themeName+"_pgLastDisabled");
		}
		
		/**
		   * 添加按钮disabled状态样式
		   */
		function disabled(){
				$(" ."+opts.themeName+"_pgNext").addClass(opts.themeName+"_pgNextDisabled");
				$(" ."+opts.themeName+"_pgPrev").addClass(opts.themeName+"_pgPrevDisabled");
				$(" ."+opts.themeName+"_pgFirst").addClass(opts.themeName+"_pgFirstDisabled");
				$(" ."+opts.themeName+"_pgLast").addClass(opts.themeName+"_pgLastDisabled");
		}
		
		
		/**
		 * This function inserts the pagination links into the container element
		 */
		function drawLinks() {
			var current = readCookie('px');
           	if (!current)
           	{
            	current = 0;
           	}
			panel.empty();
			var interval = getInterval();
			var np = numPages();
			// This helper function returns a handler function that calls pageSelected with the right page_id
			var getClickHandler = function(page_id) {
				return function(evt){ return pageSelected(page_id,evt); }
			}
			
			
			var toolbar = '<table width="100%" border="0" cellpadding="0" cellspacing="0" class="'+opts.themeName+'_pgToolbar"><tr><td>';
			toolbar += '<table border="0" cellspadding="0" cellspacing="0" class="'+opts.themeName+'_pgPanel"><tr>';
			
			toolbar += '<td valign="middle"><div class="'+opts.themeName+'_pgBtn '+opts.themeName+'_pgFirst" title="首页"></div></td>';
			toolbar += '<td valign="middle"><div class="'+opts.themeName+'_pgBtn '+opts.themeName+'_pgPrev" title="上页"></div></td>';
			
			toolbar += '<td valign="middle" width="10" align="left"><div class="'+opts.themeName+'_separator"></div></td>';
			toolbar += '<td valign="middle">第 <input class="'+opts.themeName+'_pgCurrentPage" type="text" value="' + parseInt(current_page + 1) + '" title="页码" /> 页 / 共 <span class="'+opts.themeName+'_pgTotalPage">' + numPages() + '</span> 页</td>';
			toolbar += '<td valign="middle" width="10" align="right"><div class="'+opts.themeName+'_separator"></div></td>';
			
			toolbar += '<td valign="middle"><div class="'+opts.themeName+'_pgBtn '+opts.themeName+'_pgNext" title="下页"></div></td>';
			toolbar += '<td valign="middle"><div class="'+opts.themeName+'_pgBtn '+opts.themeName+'_pgLast" title="尾页"></div></td>';
			
			toolbar += '</tr></table>';
			toolbar += '</td></tr></table>';
			
			panel.append(toolbar);
			

						
	        //首页按钮事件监听
			$(" ."+opts.themeName+"_pgFirst").click(
				function(evt){
				    var page_id = 0;
				    
				    if(page_id != current_page){
				        pageSelected(page_id,evt);
				        refresh();  
				    }
				}
			);
			
			//上一页按钮事件监听
			$(" ."+opts.themeName+"_pgPrev").click(
				function(evt){
				    var page_id = current_page - 1;
				    
				    if(page_id >= 0){
				        pageSelected(page_id,evt);
				        refresh();  
				    }
				}
			);
			
			//下一页按钮事件监听
			$(" ."+opts.themeName+"_pgNext").click(
				function(evt){
				    var page_id = current_page + 1;
				    
				    if(page_id < numPages()){
				        pageSelected(page_id,evt); 
				        refresh(); 
				    }
				}
			);	
			
			
			//末页按钮事件监听
			$(" ."+opts.themeName+"_pgLast").click(
				function(evt){
				    var page_id = numPages() -1;
				    
				    if(page_id != current_page){
				        pageSelected(page_id,evt);
				        refresh();  
				    }
				}
			);		
			
			//跳转页事件监听
			$("."+opts.themeName+"_pgCurrentPage").keydown(
	            function(event){
	                var targetPage = $(this).val() -1;
		            if(event.keyCode==13 && targetPage>=0 && targetPage<=numPages() -1){
		                 pageSelected(targetPage);
		                 refresh(); 

		            }
	            }
            );    
			
		}
		
		
		// Store DOM element for easy access from all inner functions
		var panel = jQuery(this);		
		
		if (!maxentries || maxentries < 0) {
		    var toolbar = '<table width="100%" border="0" cellpadding="0" cellspacing="0" class="'+opts.themeName+'_pgToolbar"><tr><td>';
		    toolbar += '暂无跟单记录';
		    toolbar += '</td></tr></table>';
		
		    panel.append(toolbar);
		    
		    return;
		}
		
		// Extract current_page from options
		var current_page = opts.current_page;
		// Create a sane value for maxentries and items_per_page
		maxentries = (!maxentries || maxentries < 0)?1:maxentries;
		opts.items_per_page = (!opts.items_per_page || opts.items_per_page < 0)?1:opts.items_per_page;		
		
		// When all initialisation is done, draw the links
		drawLinks();		
        
        refresh();   
        // call callback function
        opts.callback(current_page, this);
        
	});
}
/**
 * This jQuery plugin is an extension of the jquery.pagination plugin 
 * originally written by Gabriel Birke (birke *at* d-scribe *dot* de).
 *
 * Make sure jquery.pagination.js plugin is loaded before using this plugin
 *
 *
 * @author Carlo Tasca
 * @version 1.1
 *
 * PAGINATOR SETTINGS:
 *
 * @param {int} maxentries Number of entries to paginate
 * @param {string} paginatorClass CSS class for paginator
 * @param {string} paginatorContentId CSS id for paginator content
 * @param {int} itemsPerPage Number of items per page
 * @param {int} totalEntries Total of clickable entries (page numbers)
 * @param {int} currentPage Sets initial page number 
 * @param {string} elementModel Model for each entry
 * @param {string} postUrl URL for paginator data
 * @param {object} modelFieldNames object with array of fieldnames for server side database query
 */
jQuery.fn.paginator = function(settings){
	var current = this;
	settings = jQuery.extend({
		paginatorId:current,
		paginatorClass:"pagination",
		paginatorContentId:"paginator_content",
		itemsPerPage:1,
		totalEntries:10,
		currentPage:0,
		postUrl: "",
		fieldnames : ["type", "name"],
		modelFieldNames:{'modelFieldNames[]' : settings.fieldnames}
	},settings||{});
	

	function _jqueryPaginator(){
			
		      function setPaginatorData(datatext){
	            var natordata = eval(datatext);
	            function getPaginatorOptions(){
	                var opt = {callback: selectedPageNumCallback,
	                items_per_page : settings.itemsPerPage,
	                current_page: settings.currentPage,
					themeName: settings.themeName
                };
               
                return opt;
            };
            function selectedPageNumCallback(page_index, jq){
                // Get number of elements per pagionation page from form
                // get number from tot rows in news db
				createCookie('px',page_index,1);
                var items_per_page = settings.itemsPerPage;
                var max_elem = Math.min((page_index+1) * items_per_page, natordata[0].length);
                var newcontent = '';
                // Iterate through a selection of content and build an HTML string via elementModel
                for(var i=page_index*items_per_page;i<max_elem;i++)
                {
                    for(var ii = 0; ii < settings.elementModel.length; ii++)
                    {
                        element = settings.elementModel[ii].replace(/\{[0-9]{0,200}\}/g, natordata[0][i][settings.fieldnames[ii]]);
                        element = element.replace(/<(script)>|<\/?(script)[^<>]*>/ig, "");
                        newcontent += element;
                    }
                }
                // Replace old content with new content
                jQuery('#' + settings.paginatorContentId).html(newcontent);
                 
                // Prevent click eventpropagation
                return false;
            };
            // assign class to paginator element
            jQuery(settings.paginatorId).attr("class", settings.paginatorClass)
            // Create pagination element
            var optInit = getPaginatorOptions();
            jQuery(settings.paginatorId).pagination(natordata[0].length, optInit);     
       }
       jQuery.post(settings.postUrl, settings.modelFieldNames,setPaginatorData);  
	}
	return _jqueryPaginator();
}